<template>
  <view v-if="showModal" class="modal-overlay" @tap="closeModal">
    <view class="qrcode-modal" @tap.stop>
      <view class="modal-header">
        <text class="modal-title">我的推荐码</text>
        <view class="close-btn" @tap="closeModal">
          <text class="close-icon">×</text>
        </view>
      </view>

      <view class="modal-content">
        <view class="user-info">
          <image
            class="user-avatar"
            :src="getUserAvatar()"
            mode="aspectFill"
            @error="onUserAvatarError"
          />
          <view class="user-details">
            <text class="user-name">{{ userInfo.nickname || '用户' }}</text>
            <text class="invite-text">邀请您加入巴蜀客家</text>
          </view>
        </view>

        <view class="qrcode-container">
          <image
            class="qrcode-img"
            :src="qrCodeUrl"
            mode="aspectFit"
            @tap="previewQrCode"
          />
          <text class="qrcode-tip">长按二维码保存到相册</text>
        </view>

        <view class="invite-info">
          <view class="info-item">
            <text class="info-icon">🎁</text>
            <text class="info-text">加入巴蜀客家线上商城，好礼多多送。</text>
          </view>
        </view>
      </view>

      <view class="modal-actions">
        <button class="action-btn primary" @tap="saveQrCode">保存二维码</button>
        <button class="action-btn secondary" @tap="shareQrCode">分享推荐</button>
      </view>
      
      <view id="posterTemplate" class="poster-template">
        <view class="poster-background">
          <view class="poster-content">
            <view class="poster-header">
              <image class="poster-avatar" :src="getUserAvatar()" mode="aspectFill" />
              <view class="poster-user-info">
                <text class="poster-username">{{ userInfo.nickname || '用户' }}</text>
                <text class="poster-invite-text">邀请您加入巴蜀客家</text>
              </view>
            </view>
            
            <view class="poster-qr-section">
              <image class="poster-qrcode" :src="qrCodeUrl" mode="aspectFit" />
              <text class="poster-qr-tip">长按识别二维码</text>
            </view>
            
            
            
            <view class="poster-footer">
              <text class="poster-brand">巴蜀客家</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- #ifdef MP-WEIXIN -->
      <canvas 
        canvas-id="posterCanvas"
        id="posterCanvas"
        v-if="showModal"
        :style="canvasStyle"
      ></canvas>
      <!-- #endif -->
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick, getCurrentInstance } from 'vue'
import sheep from '@/sheep'

const showModal = ref(false)
const qrCodeUrl = ref('')
const instance = getCurrentInstance()

const userInfo = computed(() => sheep.$store('user').userInfo)

const canvasStyle = {
  width: '375px',
  height: '667px',
  position: 'fixed',
  left: '-9999px',
  top: '-9999px',
  zIndex: '-1',
  opacity: '0'
}

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

function openModal(url) {
  qrCodeUrl.value = url
  showModal.value = true
}

function closeModal() {
  showModal.value = false
  emit('close')
}

function previewQrCode() {
  if (qrCodeUrl.value) {
    uni.previewImage({
      urls: [qrCodeUrl.value],
      current: qrCodeUrl.value
    })
  }
}

function getUserAvatar() {
  if (userInfo.value.avatar) {
    if (userInfo.value.avatar.startsWith('http')) {
      return userInfo.value.avatar;
    }
    return sheep.$url.cdn(userInfo.value.avatar);
  }
  return 'https://git-open.oss-cn-shenzhen.aliyuncs.com/ruoyi-mall/uniapp/icons/default_avatar.png';
}

function onUserAvatarError(e) {
  e.target.src = 'https://git-open.oss-cn-shenzhen.aliyuncs.com/ruoyi-mall/uniapp/icons/default_avatar.png';
}

async function saveQrCode() {
  if (!qrCodeUrl.value) return

  try {
    if (qrCodeUrl.value.startsWith('data:image')) {
      //#ifdef H5
      const link = document.createElement('a');
      link.href = qrCodeUrl.value;
      link.download = `qrcode_${Date.now()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      sheep.$helper.toast('保存成功');
      //#endif

      //#ifndef H5
      const base64Data = qrCodeUrl.value.split(',')[1];
      const filePath = `${uni.env.USER_DATA_PATH}/qrcode_${Date.now()}.png`;

      const fs = uni.getFileSystemManager();
      fs.writeFileSync(filePath, base64Data, 'base64');

      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          sheep.$helper.toast('保存成功')
          try { fs.unlinkSync(filePath); } catch(e) {}
        },
        fail: (err) => {
          if (err.errMsg && err.errMsg.includes('auth deny')) {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存相册权限',
              showCancel: false
            })
          } else {
            sheep.$helper.toast('保存失败')
          }
          try { fs.unlinkSync(filePath); } catch(e) {}
        }
      })
      //#endif
    } else {
      uni.saveImageToPhotosAlbum({
        filePath: qrCodeUrl.value,
        success: () => {
          sheep.$helper.toast('保存成功')
        },
        fail: (err) => {
          if (err.errMsg && err.errMsg.includes('auth deny')) {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存相册权限',
              showCancel: false
            })
          } else {
            sheep.$helper.toast('保存失败')
          }
        }
      })
    }
  } catch (error) {
    sheep.$helper.toast('保存失败')
  }
}

async function shareQrCode() {
  if (!showModal.value || !qrCodeUrl.value) {
    sheep.$helper.toast('请先打开推广码')
    return
  }

  uni.showLoading({
    title: '生成分享图片...',
    mask: true
  })

  try {
    await nextTick()
    
    const posterUrl = await Promise.race([
      generateSharePoster(),
      new Promise((_, reject) => {
        setTimeout(() => {
          reject(new Error('生成超时，请重试'))
        }, 30000)
      })
    ])
    
    uni.hideLoading()
    
    if (posterUrl) {
      shareToWeChat(posterUrl)
    } else {
      throw new Error('海报生成失败，未获得图片路径')
    }
  } catch (error) {
    uni.hideLoading()
    
    uni.showModal({
      title: '生成失败',
      content: '海报生成失败，可以直接保存二维码图片分享给好友',
      showCancel: true,
      cancelText: '重试',
      confirmText: '保存二维码',
      success: (res) => {
        if (res.confirm) {
          saveQrCode()
        } else {
          setTimeout(() => shareQrCode(), 1000)
        }
      }
    })
  }
}

function shareToWeChat(imageUrl) {
  // #ifdef MP-WEIXIN
  try {
    saveImageToAlbum(imageUrl).then(filePath => {
      uni.shareWithSystem({
        type: 'image',
        imageUrl: filePath || imageUrl,
        success() {
          sheep.$helper.toast('分享成功')
        },
        fail() {
          triggerWeChatShare(imageUrl)
        }
      })
    }).catch(error => {
      triggerWeChatShare(imageUrl)
    })
  } catch (error) {
    triggerWeChatShare(imageUrl)
  }
  // #endif
  
  // #ifdef H5
  triggerWeChatShare(imageUrl)
  // #endif
}

function saveImageToAlbum(imageUrl) {
  return new Promise((resolve, reject) => {
    if (imageUrl.startsWith('data:image')) {
      //#ifndef H5
      const base64Data = imageUrl.split(',')[1];
      const filePath = `${uni.env.USER_DATA_PATH}/share_poster_${Date.now()}.png`;

      const fs = uni.getFileSystemManager();
      fs.writeFileSync(filePath, base64Data, 'base64');

      uni.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          resolve(filePath)
          try { fs.unlinkSync(filePath); } catch(e) {}
        },
        fail: (err) => {
          reject(err)
          try { fs.unlinkSync(filePath); } catch(e) {}
        }
      })
      //#endif
    } else {
      uni.saveImageToPhotosAlbum({
        filePath: imageUrl,
        success: () => {
          resolve(imageUrl)
        },
        fail: (err) => {
          reject(err)
        }
      })
    }
  })
}

function triggerWeChatShare(imageUrl) {
  // #ifdef MP-WEIXIN
  uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    uni.updateShareMenu({
      withShareTicket: true,
      isUpdatableMessage: false,
      templateInfo: {
        parameterList: [{
          name: 'member_count',
          value: '1'
        }]
      }
    })
  
  uni.showModal({
    title: '分享海报',
    content: '点击右上角分享按钮，将推荐码发送给微信好友',
    showCancel: false,
    confirmText: '立即分享',
    success: () => {
      uni.showShareImageMenu({
          path: imageUrl
        })
    }
  })
  // #endif
  
  // #ifdef H5
  uni.showModal({
    title: '分享海报', 
    content: '长按图片保存到相册，然后发送给好友',
    showCancel: false,
    confirmText: '知道了'
  })
  // #endif
}

async function generateSharePoster() {
  return new Promise(async (resolve, reject) => {
    try {
      //#ifdef H5
      await generatePosterByHTML(resolve, reject)
      //#endif
      
      //#ifdef MP-WEIXIN
      await generatePosterByCanvas(resolve, reject)
      //#endif
      
      //#ifndef H5 || MP-WEIXIN
      reject('暂不支持当前平台')
      //#endif
    } catch (error) {
      reject(`生成失败: ${error}`)
    }
  })
}

async function generatePosterByHTML(resolve, reject) {
  try {
    const posterElement = document.getElementById('posterTemplate')
    if (!posterElement) {
      reject('海报模板未找到')
      return
    }
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    canvas.width = 375
    canvas.height = 667
    
    await drawSimplePoster(ctx, 375, 667)
    
    const dataURL = canvas.toDataURL('image/png', 1.0)
    resolve(dataURL)
  } catch (error) {
    reject(`H5生成失败: ${error}`)
  }
}

async function generatePosterByCanvas(resolve, reject) {
  try {
    const width = 375
    const height = 667
    
    await nextTick()
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const ctx = uni.createCanvasContext('posterCanvas', instance.proxy)
    
    if (!ctx) {
      reject('无法创建Canvas上下文')
      return
    }
    
    ctx.clearRect(0, 0, width, height)
    
    ctx.setFillStyle('#8B4513')
    ctx.fillRect(0, 0, width, height)
    
    ctx.setFillStyle('#ffffff')
    ctx.fillRect(20, 120, width - 40, height - 200)
    
    ctx.setFillStyle('#333333')
    ctx.setFontSize(18)
    ctx.setTextAlign('center')
    ctx.fillText(userInfo.value.nickname || '用户', width / 2, 200)
    
    ctx.setFillStyle('#666666')
    ctx.setFontSize(14)
    ctx.fillText('邀请您加入巴蜀客家', width / 2, 230)
    
    const qrSize = 120
    const qrX = (width - qrSize) / 2
    const qrY = 280
    
    try {
      if (qrCodeUrl.value) {
        if (qrCodeUrl.value.startsWith('data:image')) {
          const tempFilePath = await saveBase64ToTemp(qrCodeUrl.value)
          ctx.drawImage(tempFilePath, qrX, qrY, qrSize, qrSize)
        } else if (qrCodeUrl.value.startsWith('http')) {
          const tempFilePath = await downloadImage(qrCodeUrl.value)
          ctx.drawImage(tempFilePath, qrX, qrY, qrSize, qrSize)
        } else {
          ctx.drawImage(qrCodeUrl.value, qrX, qrY, qrSize, qrSize)
        }
      } else {
        ctx.setStrokeStyle('#ddd')
        ctx.setLineWidth(2)
        ctx.strokeRect(qrX, qrY, qrSize, qrSize)
      }
    } catch (error) {
      ctx.setStrokeStyle('#ddd')
      ctx.setLineWidth(2)
      ctx.strokeRect(qrX, qrY, qrSize, qrSize)
    }
    
    ctx.setFillStyle('#999999')
    ctx.setFontSize(12)
    ctx.fillText('长按识别二维码', width / 2, qrY + qrSize + 30)
    
    ctx.setFillStyle('#8B4513')
    ctx.setFontSize(14)
    ctx.fillText('🎁 加入巴蜀客家线上商城，好礼多多送', width / 2, 500)

    
    ctx.setFillStyle('#DAA520')
    ctx.setFontSize(14)
    ctx.fillText('巴蜀客家 - 传承千年文化', width / 2, height - 50)
    
    ctx.draw(true, () => {
      setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: 'posterCanvas',
          x: 0,
          y: 0,
          width: width,
          height: height,
          destWidth: width * 2,
          destHeight: height * 2,
          fileType: 'png',
          quality: 1,
          success: (res) => {
            resolve(res.tempFilePath)
          },
          fail: (err) => {
            reject(`生成图片失败: ${err.errMsg || JSON.stringify(err)}`)
          }
        }, instance.proxy)
      }, 1500)
    })
    
  } catch (error) {
    reject(`小程序生成失败: ${error.message || error}`)
  }
}

function saveBase64ToTemp(base64Data) {
  return new Promise((resolve, reject) => {
    const base64 = base64Data.split(',')[1]
    const filePath = `${uni.env.USER_DATA_PATH}/temp_qr_${Date.now()}.png`
    
    const fs = uni.getFileSystemManager()
    fs.writeFile({
      filePath: filePath,
      data: base64,
      encoding: 'base64',
      success: () => {
        resolve(filePath)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

function downloadImage(imageUrl) {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: imageUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath)
        } else {
          reject('下载图片失败')
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

async function drawSimplePoster(ctx, width, height) {
  ctx.fillStyle = 'linear-gradient(135deg, #8B4513 0%, #DAA520 50%, #8B4513 100%)'
  ctx.fillRect(0, 0, width, height)
  
  ctx.fillStyle = '#ffffff'
  ctx.fillRect(20, 120, width - 40, height - 200)
  
  ctx.fillStyle = '#333333'
  ctx.font = '18px Arial'
  ctx.textAlign = 'center'
  ctx.fillText(userInfo.value.nickname || '用户', width / 2, 200)
  
  ctx.fillStyle = '#666666'
  ctx.font = '14px Arial'
  ctx.fillText('邀请您加入巴蜀客家', width / 2, 230)
  
  if (qrCodeUrl.value) {
    try {
      const img = new Image()
      img.crossOrigin = 'anonymous'
      await new Promise((resolve, reject) => {
        img.onload = resolve
        img.onerror = reject
        img.src = qrCodeUrl.value
      })
      
      const qrSize = 120
      const qrX = (width - qrSize) / 2
      const qrY = 280
      ctx.drawImage(img, qrX, qrY, qrSize, qrSize)
    } catch (error) {
    }
  }
  
  ctx.fillStyle = '#999999'
  ctx.font = '12px Arial'
  ctx.fillText('长按识别二维码', width / 2, 450)
  
  ctx.fillStyle = '#8B4513'
  ctx.font = '16px Arial'
  ctx.fillText('🎁 加入巴蜀客家线上商城，好礼多多送。', width / 2, 500)
  
  ctx.fillStyle = '#DAA520'
  ctx.font = '14px Arial'
  ctx.fillText('巴蜀客家 - 传承千年文化', width / 2, height - 50)
}

defineExpose({
  openModal,
  closeModal
})
</script>

<style lang="scss" scoped>
$primary-color: #8B4513;
$secondary-color: #DAA520;
$accent-color: #228B22;

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.qrcode-modal {
  width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);

  .modal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: white;
  }

  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: rgba(white, 0.2);

    .close-icon {
      font-size: 40rpx;
      color: white;
      font-weight: bold;
    }
  }
}

.modal-content {
  padding: 40rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;

  .user-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin-right: 24rpx;
    border: 4rpx solid #f0f0f0;
  }

  .user-details {
    flex: 1;

    .user-name {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: 8rpx;
    }

    .invite-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;

  .qrcode-img {
    width: 300rpx;
    height: 300rpx;
    border-radius: 16rpx;
    border: 2rpx solid #f0f0f0;
    margin-bottom: 20rpx;
  }

  .qrcode-tip {
    font-size: 24rpx;
    color: #999;
  }
}

.invite-info {
  margin-bottom: 20rpx;

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .info-icon {
      font-size: 32rpx;
      margin-right: 16rpx;
    }

    .info-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

.modal-actions {
  display: flex;
  gap: 20rpx;
  padding: 0 40rpx 40rpx;

  .action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    font-weight: bold;
    border: none;

    &.primary {
      background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
      color: white;
    }

    &.secondary {
      background: #f8f8f8;
      color: $primary-color;
      border: 2rpx solid $primary-color;
    }

    &:active {
      opacity: 0.8;
    }
  }
}

.poster-template {
  position: absolute !important;
  top: -9999px !important;
  left: -9999px !important;
  opacity: 0 !important;
  pointer-events: none !important;
  z-index: -999 !important;
  width: 375px;
  height: 667px;
  overflow: hidden;
}

.poster-background {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #8B4513 0%, #DAA520 50%, #8B4513 100%);
  position: relative;
}

.poster-content {
  position: absolute;
  top: 80px;
  left: 20px;
  right: 20px;
  bottom: 80px;
  background: #ffffff;
  border-radius: 16px;
  padding: 30px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.poster-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  
  .poster-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 16px;
    border: 3px solid #f0f0f0;
  }
  
  .poster-user-info {
    flex: 1;
    
    .poster-username {
      display: block;
      font-size: 18px;
      font-weight: bold;
      color: #333333;
      margin-bottom: 4px;
    }
    
    .poster-invite-text {
      display: block;
      font-size: 14px;
      color: #666666;
    }
  }
}

.poster-qr-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  
  .poster-qrcode {
    width: 120px;
    height: 120px;
    border-radius: 8px;
    margin-bottom: 10px;
  }
  
  .poster-qr-tip {
    font-size: 12px;
    color: #999999;
  }
}

.poster-rewards {
  margin-bottom: 30px;
  
  .poster-reward-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    
    .poster-reward-icon {
      font-size: 16px;
      margin-right: 8px;
    }
    
    .poster-reward-text {
      font-size: 16px;
      color: #8B4513;
    }
  }
}

.poster-footer {
  margin-top: auto;
  
  .poster-brand {
    font-size: 14px;
    color: #DAA520;
    font-weight: bold;
  }
}

.poster-canvas {
  visibility: hidden;
}
</style>